package com.mmall.service;

import com.google.common.base.Joiner;
import com.mmall.beans.CacheKeyConstants;
import com.mmall.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;

import javax.annotation.Resource;

@Service
@Slf4j
public class SysCacheService {
	// 调用了单独的RedisPool的service
	@Resource(name = "redisPool")
	private RedisPool redisPool;

	/**
	 * 存入缓存
	 * 
	 * @param toSavedValue
	 *            存入的数据
	 * @param timeoutSeconds
	 *            超时数据
	 * @param prefix
	 *            前缀
	 */
	public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix) {
		saveCache(toSavedValue, timeoutSeconds, prefix, null);
	}

    /**
     * 新增
     * @param toSavedValue
     * @param timeoutSeconds
     * @param prefix
     * @param keys
     */
	public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix, String... keys) {
		if (toSavedValue == null) {
			return;
		}
		ShardedJedis shardedJedis = null;
		try {
			String cacheKey = generateCacheKey(prefix, keys);
			shardedJedis = redisPool.instance();
			shardedJedis.setex(cacheKey, timeoutSeconds, toSavedValue);

		} catch (Exception e) {
			log.error("redis保存失败，prefix:{}，keys:{},异常：{}\n", prefix.name(), JsonMapper.objToString(keys), e);
		} finally {
			redisPool.safeClose(shardedJedis);
		}
	}

    /**
     * 获取
     * @param prefix
     * @param keys
     * @return
     */
	public String getFromCache(CacheKeyConstants prefix,String... keys){
        ShardedJedis shardedJedis = null;
        String cacheKey = generateCacheKey(prefix,keys);
        try {
           shardedJedis = redisPool.instance();
           String value = shardedJedis.get(cacheKey);
           return value;
        }catch (Exception e){
            log.error("redis保存失败，prefix:{}，keys:{},异常：{}\n", prefix.name(), JsonMapper.objToString(keys), e);
        }finally {
            redisPool.safeClose(shardedJedis);
        }
        return null;
    }

    /**
     * 生成key
     * @param prefix
     * @param keys
     * @return
     */
	private String generateCacheKey(CacheKeyConstants prefix, String... keys) {
		String key = prefix.name();
		if (keys != null && keys.length > 0) {
			key += "_" + Joiner.on("_").join(keys);
		}
		return key;
	}
}
